package com.robotserver.orders.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.robotserver.orders.common.DateFormatUtil;
import com.robotserver.orders.common.DateUtil;
import com.robotserver.orders.common.Math;
import com.robotserver.orders.common.Tools;
import com.robotserver.orders.constant.CacheKey;
import com.robotserver.orders.entity.AlimmTokens;
import com.robotserver.orders.entity.TbOrders;
import com.robotserver.orders.enums.BizStatus;
import com.robotserver.orders.mapper.AlimmTokensMapper;
import com.robotserver.orders.mapper.TbOrdersMapper;
import com.robotserver.orders.service.OrdersNotifyService;
import com.robotserver.orders.service.RatelimitService;
import com.robotserver.orders.service.TbOrderSyncService;
import com.robotserver.orders.service.TbSettleOrderSyncService;
import com.robotserver.orders.vo.TbkOrderTimeVO;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.taobao.api.request.TbkScOrderDetailsGetRequest;
import com.taobao.api.response.TbkScOrderDetailsGetResponse;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: liuqi
 * @Date: 2021/4/28 11:16
 * @Description:
 */
@Service
public class TbOrderSyncServiceImpl implements TbOrderSyncService {

    private static Logger logger = LoggerFactory.getLogger(TbOrderSyncServiceImpl.class);

    @Autowired
    private TbOrdersMapper tbOrdersMapper;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private AlimmTokensMapper alimmTokensMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrdersNotifyService ordersNotifyService;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static long pagesize = 100;
    private static long querytype = 4; // 更新时间
    private static long tkstatus = 3;  // 状态为结算订单
    private static long jumptype = 1;  // 向前翻页

    @Override
    public void syncAlimmUnitOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, AlimmTokens alimmTokens, TaobaoClient client,Long orderScene) {
        for (TbkOrderTimeVO tbkOrderTimeVO:tbkOrderTimeVOList){
            syncTimeUnitOrder(tbkOrderTimeVO,alimmTokens,client,null,1l,orderScene);
        }
    }

    @Override
    public void syncTimeUnitOrder(TbkOrderTimeVO tbkOrderTime, AlimmTokens alimmTokens, TaobaoClient client,String positionindex,Long pageNo,Long orderScene) {
        try {
            //淘宝联盟限流-单个联盟每2秒调用1次
            boolean inRateLimit = ratelimitService.inRateLimit("tbPullOrder-tokenUserId="+alimmTokens.getUserId(),CacheKey.tb_token_ratelimit, 1);

            //判断最多循环40次，每次睡眠50毫秒，总共1秒
            int flag = 0;
            while (!inRateLimit){
                flag ++;
                if(flag>40){
                    //对象转成JSON字符串，保存到redis队列中
                    AlimmTokens alimmTokens_new = new AlimmTokens();
                    BeanUtils.copyProperties(alimmTokens, alimmTokens_new);
                    alimmTokens_new.setBeginTime(Long.valueOf(DateUtil.getTime(DateFormatUtil.StringToDateFormat(tbkOrderTime.getBeginTime()))));
                    alimmTokens_new.setEndTime(Long.valueOf(DateUtil.getTime(DateFormatUtil.StringToDateFormat(tbkOrderTime.getEndTime()))));
                    String alimmTokensStr = JSONObject.toJSONString(alimmTokens_new);
                    redisTemplate.opsForList().leftPush(alimmTokens_new.getRedisQueueKey(), alimmTokensStr);
                    return;
                }
                Thread.sleep(50);
                inRateLimit = ratelimitService.inRateLimit("tbPullOrder-tokenUserId="+alimmTokens.getUserId(),CacheKey.tb_token_ratelimit,1);
            }

            if(alimmTokens.getTimeType() != null){
                querytype = alimmTokens.getTimeType();
            }else{
                querytype = 4; //如果下载类型为空，则默认按照订单更新时间来下载
            }

            TbkScOrderDetailsGetRequest req = new TbkScOrderDetailsGetRequest();
            //logger.info("------JOB任务拉取订单-------"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
            req.setQueryType(querytype);
            if (StringUtils.isNotBlank(positionindex)){
                req.setPositionIndex(positionindex);
            }
            req.setPageSize(pagesize);
            //req.setTkStatus(tkstatus);
            req.setStartTime(tbkOrderTime.getBeginTime());
            req.setEndTime(tbkOrderTime.getEndTime());
            req.setJumpType(jumptype);
            req.setPageNo(pageNo);
            req.setOrderScene(orderScene);
            TbkScOrderDetailsGetResponse rsp = client.execute(req, alimmTokens.getAccessToken());

            //限流问题
            if("9100".equals(rsp.getSubCode())){
                logger.error("--error--淘宝拉取遇到限流问题，将此token重新push到redis队列当中-------sub_msg=" + rsp.getSubMsg()+ "::" + "orderScene="+orderScene+"::"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
                //对象转成JSON字符串，保存到redis队列中
                String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                redisTemplate.opsForList().leftPush(alimmTokens.getRedisQueueKey(), alimmTokensStr);

                //限流判断(30秒内超过10次)
                //boolean inRateLimit = ratelimitService.inRateLimit(String.format(CacheKey.tbOrderErrorNotify, "33931400"),10,30);
                //if (!inRateLimit){
                //发送消息提醒
                //Object val = redisTemplate.opsForValue().get(String.format(CacheKey.tbOrderErrorNotify, "33931400"));
                //if (val == null){
                SimpleDateFormat tbkFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
                String downTime = tbkFormat.format(new Date());
                String content = "--error-下载限流--下载时间="+downTime+"::userName="+alimmTokens.getUserName() + "::orderScene=" + orderScene +"::querytype="+ querytype +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo +"::subMsg=" + rsp.getSubMsg();
                ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content);
                //往reids插入本次下载，允许5分钟调用一次
                //redisTemplate.opsForValue().set(String.format(CacheKey.tbOrderErrorNotify, "33931400"),alimmTokens.getUserId()+"",10, TimeUnit.MINUTES);
                //}
                //}
            }else if("3001".equals(rsp.getSubCode()) && rsp.getData() == null){
                logger.error("--error--系统繁忙，将此token重新push到redis队列当中-------sub_msg=" + rsp.getSubMsg()+ "::" + "orderScene="+orderScene+"::"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
                //遇到系统繁忙，延迟1秒再次调用
                Thread.sleep(1000);
                rsp = client.execute(req, alimmTokens.getAccessToken());
                if("3001".equals(rsp.getSubCode()) && rsp.getData() == null){
                    logger.error("----遇到系统第二次繁忙--将此token重新push到redis队列当中-------orderScene="+orderScene+"::"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
                    //对象转成JSON字符串，保存到redis队列中
                    String alimmTokensStr = JSONObject.toJSONString(alimmTokens);
                    redisTemplate.opsForList().leftPush(alimmTokens.getRedisQueueKey(), alimmTokensStr);

//                    logger.error("--error--遇到系统繁忙-重复调用再次遇到系统繁忙，将此token重新push到redis队列当中-------sub_msg=" + rsp.getSubMsg()+ "::" + "orderScene="+orderScene+"::"+alimmTokens.getAccessToken()+"::"+alimmTokens.getUserName()+"::"+tbkOrderTime.getBeginTime()+"::"+tbkOrderTime.getEndTime());
//                    SimpleDateFormat tbkFormat_repay = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
//                    String downTime_repay = tbkFormat_repay.format(new Date());
//                    String content_repay = "--error-调用API系统繁忙--下载时间="+downTime_repay+ "::userName="+alimmTokens.getUserName() + "::orderScene=" + orderScene +"::querytype="+ querytype +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo +"::subMsg=" + rsp.getSubMsg();
//                    ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content_repay);

                }
            }else{
//                //下载成功，监控 捕风客003 下载频率
//                if(alimmTokens.getUserName().equals("捕风客003")){
//                    SimpleDateFormat tbkFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSS");
//                    String downTime = tbkFormat.format(new Date());
//                    String content = "--下载成功--下载时间="+downTime+"::userName="+alimmTokens.getUserName() + "::orderScene=" + orderScene +"::querytype="+ querytype +"::beginTime="+tbkOrderTime.getBeginTime()+"::endTime="+tbkOrderTime.getEndTime() +"::paneNo=" +  pageNo;
//                    ordersNotifyService.tbOrderRomoteLimit(alimmTokens.getUserId(), content);
//                }
            }

            // 处理入库
            if (rsp.getData()!=null){
                ordersAdd(rsp.getData().getResults(),alimmTokens);
                if (rsp.getData().getHasNext()){
                    pageNo = pageNo+1;
                    syncTimeUnitOrder(tbkOrderTime,alimmTokens,client,rsp.getData().getPositionIndex(),pageNo, orderScene);
                }else{
                    // 修改心跳
                    if (alimmTokens.getId()!=null){
                        int now = DateUtil.getNowTime();
                        alimmTokensMapper.updateSettleHeartbeat(alimmTokens.getId(),now);
                    }
                }
            }else {
                // 修改心跳
                if (alimmTokens.getId()!=null){
                    int now = DateUtil.getNowTime();
                    alimmTokensMapper.updateSettleHeartbeat(alimmTokens.getId(),now);
                }
            }

        } catch (Exception e) {
            logger.error("sync tb settlement order err:",e);
        }
    }

    @Transactional
    @Override
    public void ordersAdd(List<TbkScOrderDetailsGetResponse.PublisherOrderDto> orders,AlimmTokens alimmTokens) {
        int now = DateUtil.getNowTime();
        if (orders==null || orders.size()==0){
            return ;
        }
        for (TbkScOrderDetailsGetResponse.PublisherOrderDto order:orders){
            //修改时间
            Date modifyTimeDate = DateFormatUtil.StringToDateFormat(order.getModifiedTime(),"yyyy-MM-dd HH:mm:ss");
            Integer modifyTime = DateUtil.getTime(modifyTimeDate);
            //支付总金额
            int alipayTotalPrice = Math.currencyFormatToF(order.getAlipayTotalPrice());

            // 查询订单是否存在
            TbOrders tbOrder = tbOrdersMapper.getByOrderNo(order.getTradeParentId(),order.getTradeId());
            if (tbOrder!=null){

                //如果淘宝状态都不变，则不修改
                if(tbOrder.getTkStatus().intValue() == order.getTkStatus().intValue()
                        && Tools.getInteger(tbOrder.getModifiedTime()).intValue() == Tools.getInteger(modifyTime).intValue()
                        && Tools.getInteger(tbOrder.getAlipayTotalPrice()).intValue() == alipayTotalPrice
                        ){
                    continue;
                }


//                if (tbOrder.getTkStatus().intValue()==order.getTkStatus().intValue()){
//                    if(order.getSpecialId() == null || (order.getSpecialId() != null && tbOrder.getSpecialId() !=null && order.getSpecialId().longValue() == tbOrder.getSpecialId().longValue())){
//                        if(order.getRelationId() == null || (order.getRelationId() != null && tbOrder.getRelationId() != null && order.getRelationId().longValue() == tbOrder.getRelationId().longValue())){
//                            continue;
//                        }
//                    }
//                }else {
                    // 修改
                    logger.info("---TB order update:parentId: {},childId: {},tkstatus:{},specialId:{},relationId:{}",new Object[]{order.getTradeParentId(),order.getTradeId(),order.getTkStatus(),order.getSpecialId(),order.getRelationId()});

                    tbOrder.setUpdateTime(now);
                    tbOrder.setAdzoneId(order.getAdzoneId());
                    tbOrder.setAdzoneName(order.getAdzoneName());
                    tbOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                    tbOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                    tbOrder.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
                    tbOrder.setAlimmUserName(alimmTokens.getUserName());
                    tbOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                    tbOrder.setAppKey(order.getAppKey());

                    //modify by 2021-03-10 18:00 by liuqi
                    tbOrder.setAlscId(order.getAlscId());
                    tbOrder.setAlscPid(order.getAlscPid());
                    tbOrder.setLxRid(order.getLxRid());
                    tbOrder.setIsLx(order.getIsLx());
                    tbOrder.setMarketingType(order.getMarketingType());
                    tbOrder.setModifiedTime(modifyTime);

                    tbOrder.setBizStatus(getStatus(order.getTkStatus().intValue()));
                    tbOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                    tbOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                    tbOrder.setFlowSource(order.getFlowSource());
                    tbOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                    tbOrder.setItemCategoryName(order.getItemCategoryName());
                    tbOrder.setItemId(order.getItemId());
                    tbOrder.setItemImg(order.getItemImg());
                    tbOrder.setItemLink(order.getItemLink());
                    tbOrder.setItemNum(order.getItemNum());
                    tbOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                    tbOrder.setItemTitle(order.getItemTitle());
                    tbOrder.setOrderType(order.getOrderType());
                    tbOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                    tbOrder.setPubId(order.getPubId());
                    tbOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                    tbOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                    tbOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                    tbOrder.setRefundTag((int) order.getRefundTag().longValue());

                    String sellerNick = order.getSellerNick();
                    if(StringUtils.isNotBlank(sellerNick)){
                        tbOrder.setSellerNick(sellerNick.length() > 32? sellerNick.substring(0,30) : sellerNick);
                    }

                    tbOrder.setSellerShopTitle(order.getSellerShopTitle());
                    tbOrder.setSiteId(order.getSiteId());
                    tbOrder.setSiteName(order.getSiteName());
                    tbOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                    tbOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                    tbOrder.setSubsidyType(order.getSubsidyType());
                    tbOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                    tbOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                    tbOrder.setTerminalType(order.getTerminalType());
                    tbOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                    tbOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                    tbOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                    tbOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                    tbOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                    tbOrder.setTkOrderRole(order.getTkOrderRole());
                    tbOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                    tbOrder.setTradeId(order.getTradeId());
                    tbOrder.setTradeParentId(order.getTradeParentId());
                    tbOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                    tbOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                    tbOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                    tbOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                    tbOrder.setPid("mm_"+order.getPubId()+"_"+order.getSiteId()+"_"+order.getAdzoneId());

                    //更新会员ID
                    if (tbOrder.getSpecialId()==null && order.getSpecialId()!=null){
                        tbOrder.setSpecialId(order.getSpecialId());
                    }
                    //更新渠道ID
                    if (tbOrder.getRelationId()==null && order.getRelationId()!=null){
                        tbOrder.setRelationId(order.getRelationId());
                    }

                    //更新订单状态
                    if (tbOrder.getTkStatus().intValue() != order.getTkStatus().intValue()){
                        tbOrder.setTkStatus((int)order.getTkStatus().longValue());
                    }

                    //更新订单
                    try {
                        tbOrdersMapper.update(tbOrder);
                    }catch (Exception e){
                        logger.error("TB order update error:parentId=" +  order.getTradeParentId()+"::childId="+order.getTradeId()+ ",异常信息:", e);
                    }
//                }
            }else {

                //添加
//                if (order.getTkStatus().intValue() == 13){ //失效订单，不插入
//                    continue;
//                }

                logger.info("---TB order add:parentId: {},childId: {},tkstatus:{}", new Object[]{order.getTradeParentId(),order.getTradeId(),order.getTkStatus()});

                TbOrders newOrder = new TbOrders();
                newOrder.setId(IdWorker.getId());
                newOrder.setCreateTime(now);
                newOrder.setUpdateTime(now);
                newOrder.setAdzoneId(order.getAdzoneId());
                newOrder.setAdzoneName(order.getAdzoneName());
                newOrder.setAlimamaRate(Math.strToDouble(order.getAlimamaRate()));
                newOrder.setAlimamaShareFee(Math.currencyFormatToF(order.getAlimamaShareFee()));
                newOrder.setAlimmUserId(String.valueOf(alimmTokens.getUserId()));
                newOrder.setAlimmUserName(alimmTokens.getUserName());
                newOrder.setAlipayTotalPrice(Math.currencyFormatToF(order.getAlipayTotalPrice()));
                newOrder.setAppKey(order.getAppKey());

                //modify by 2021-03-10 18:00 by liuqi
                newOrder.setAlscId(order.getAlscId());
                newOrder.setAlscPid(order.getAlscPid());
                newOrder.setLxRid(order.getLxRid());
                newOrder.setIsLx(order.getIsLx());
                newOrder.setMarketingType(order.getMarketingType());
                newOrder.setModifiedTime(modifyTime);

                newOrder.setBizStatus(getStatus(order.getTkStatus().intValue()));
                newOrder.setClickTime(DateUtil.getStrTime(order.getClickTime()));
                newOrder.setDepositPrice(Math.currencyFormatToF(order.getDepositPrice()));
                newOrder.setFlowSource(order.getFlowSource());
                newOrder.setIncomeRate(Math.strToDouble(order.getIncomeRate()));
                newOrder.setItemCategoryName(order.getItemCategoryName());
                newOrder.setItemId(order.getItemId());
                newOrder.setItemImg(order.getItemImg());
                newOrder.setItemLink(order.getItemLink());
                newOrder.setItemNum(order.getItemNum());
                newOrder.setItemPrice(Math.currencyFormatToF(order.getItemPrice()));
                newOrder.setItemTitle(order.getItemTitle());

                newOrder.setOrderType(order.getOrderType());
                newOrder.setPayPrice(Math.currencyFormatToF(order.getPayPrice()));
                newOrder.setPubId(order.getPubId());
                newOrder.setPubShareFee(Math.currencyFormatToF(order.getPubShareFee()));
                newOrder.setPubSharePreFee(Math.currencyFormatToF(order.getPubSharePreFee()));
                newOrder.setPubShareRate(Math.strToDouble(order.getPubShareRate()));
                newOrder.setRefundTag((int) order.getRefundTag().longValue());
                newOrder.setRelationId(order.getRelationId());

                String sellerNick = order.getSellerNick();
                if(StringUtils.isNotBlank(sellerNick)){
                    newOrder.setSellerNick(sellerNick.length() > 32 ? sellerNick.substring(0,30) : sellerNick);
                }

                newOrder.setSellerShopTitle(order.getSellerShopTitle());
                newOrder.setSiteId(order.getSiteId());
                newOrder.setSiteName(order.getSiteName());
                newOrder.setSpecialId(order.getSpecialId());
                newOrder.setSubsidyRate(Math.strToDouble(order.getSubsidyRate()));
                newOrder.setSubsidyFee(Math.currencyFormatToF(order.getSubsidyFee()));
                newOrder.setSubsidyType(order.getSubsidyType());
                newOrder.setTbDepositTime(DateUtil.getStrTime(order.getTbDepositTime()));
                newOrder.setTbPaidTime(DateUtil.getStrTime(order.getTbPaidTime()));
                newOrder.setTerminalType(order.getTerminalType());
                newOrder.setTkCommissionFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionFeeForMediaPlatform()));
                newOrder.setTkCommissionPreFeeForMediaPlatform(Math.currencyFormatToF(order.getTkCommissionPreFeeForMediaPlatform()));
                newOrder.setTkCommissionRateForMediaPlatform(Math.strToDouble(order.getTkCommissionRateForMediaPlatform()));
                newOrder.setTkCreateTime(DateUtil.getStrTime(order.getTkCreateTime()));
                newOrder.setTkEarningTime(DateUtil.getStrTime(order.getTkEarningTime()));
                newOrder.setTkOrderRole(order.getTkOrderRole());
                newOrder.setTkPaidTime(DateUtil.getStrTime(order.getTkPaidTime()));
                newOrder.setTradeId(order.getTradeId());
                newOrder.setTradeParentId(order.getTradeParentId());
                newOrder.setTkTotalRate(Math.strToDouble(order.getTkTotalRate()));
                newOrder.setTkStatus((int) order.getTkStatus().longValue());
                newOrder.setTotalCommissionRate(Math.strToDouble(order.getTotalCommissionRate()));
                newOrder.setTotalCommissionFee(Math.currencyFormatToF(order.getTotalCommissionFee()));
                newOrder.setTkDepositTime(DateUtil.getStrTime(order.getTkDepositTime()));
                newOrder.setPid("mm_" + order.getPubId() + "_" + order.getSiteId() + "_" + order.getAdzoneId());
                try {
                    tbOrdersMapper.add(newOrder);
                }catch (Exception e){
                    logger.error("TB order add error:parentId=" +  order.getTradeParentId()+"::childId="+order.getTradeId()+ ",异常信息:", e);
                }
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, List<AlimmTokens> alimmTokens, TaobaoClient client,  String lockName,Long orderScene) {
        threadLockSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lockName,orderScene);
    }

    @Override
    public void threadLockSyncOrder(List<TbkOrderTimeVO> tbkOrderTimeVOList, List<AlimmTokens> alimmTokens, TaobaoClient client,  String lockName,Long orderScene) {

        if (alimmTokens.size()>0){
            AlimmTokens token = null;
            RLock lock = null;
            try {
                lock = redissonClient.getLock(lockName);
                lock.lock();
                token = alimmTokens.get(0);
                // 删除对象
                alimmTokens.remove(token);

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (lock!=null){
                    lock.unlock();
                }
            }
            if (token!=null){
                logger.info(lockName+"::token>"+token.getUserId());
                syncAlimmUnitOrder(tbkOrderTimeVOList,token,client,orderScene);
                threadLockSyncOrder(tbkOrderTimeVOList,alimmTokens,client,lockName,orderScene);
            }
        }
    }

    @Async("taskExecutor")
    @Override
    public void threadSyncOrder_consumer(List<TbkOrderTimeVO> tbkOrderTimeVOList, AlimmTokens alimmTokens, TaobaoClient client, Long orderScene) {
        syncAlimmUnitOrder(tbkOrderTimeVOList,alimmTokens,client,orderScene);
    }


    private int getStatus(int orderStatus){
        switch (orderStatus){
            case 12:
                return 0; //付款订单
            case 13:
                return 2; //失效订单
            case 14:
                return 1; //结算订单
            case 3:
                return 1; //结算订单
        }
        return 0;
    }

    public Integer getInteger(Integer v) {
        if (v == null) {
            return 0;
        }
        return v;
    }

}
